package me.jiatao.plugindemo;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import dalvik.system.DexClassLoader;
import me.jiatao.baselib.ICommon;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "11111111111";
    private static final String APK_1 = "plugin1.apk";
    private static final String APK_2 = "plugin2.apk";

    private Context context;
    private TextView textView;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        textView = findViewById(R.id.text_view);
        imageView = findViewById(R.id.image_view);
    }


    @Override
    public AssetManager getAssets() {
        return AssetUtils.sAssetManager == null ? super.getAssets() : AssetUtils.sAssetManager;
    }

    @Override
    public Resources getResources() {
        return AssetUtils.sResources == null ? super.getResources() : AssetUtils.sResources;
    }


    public void loadPlugin(View view) {
        AssetUtils.copyAssetsPlugin2Files(context, APK_1);

        AssetUtils.extractInfo(context, APK_1);
        PluginInfo pluginInfo = AssetUtils.getPluginInfo(APK_1);
        AssetUtils.addAssetPath(getBaseContext(), APK_1);

        DexClassLoader classLoader = pluginInfo.getClassLoader();
        try {
            Class PluginResources = classLoader.loadClass("me.jiatao.plugin1.PluginResources");
            ICommon pluginObject = (ICommon) PluginResources.newInstance();

//            textView.setText(pluginObject.getString());
//            imageView.setImageResource(pluginObject.getDrawable());

            setContentView(pluginObject.getLayout());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

    }
}
